using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Linq;
using System.IO;
using Microsoft.SharePoint.WebPartPages;
using System.Drawing;

using Microsoft.SharePoint.WebControls;
using Adartse.Sharepoint.WebPartCode;
using Adartse.Sharepoint.Interfaces;
using Adartse.Sharepoint.WebPartEditors;

namespace Adartse.Sharepoint
{
    [Guid("4c1a650d-488a-447d-a4cd-b58a80ad6f55")]
    public class AWPListItem : AWPBase, IWebEditable, IShowableWebPart, IHideableWebPart
    {
        public string ItemParameter { get; set; }        
        public string ListName { get; set; }
        public string HtmlContent { get; set; }
        public string HeaderContent { get; set; }
        public string ContainterID { get; set; }
        public string ContainerClass { get; set; }
        public bool IsIDEnabled { get; set; }
        public bool IsClassEnabled { get; set; }
        //new
        public bool IsByView { get; set; }
        public string ViewName { get; set; }

        public bool EnablePreviusNextLinks  { get; set; }
        public bool GotPrevious { get; set; }
        public bool GotNext { get; set; }

        public string PreviusText { get; set; }
        public string NextText { get; set; }

        public string FolderParameter { get; set; }
        public bool EnableFolderParameter { get; set; }

        public string EmptyTemplate { get; set; }

        internal Dictionary<string, string> FieldList { get; set; }

        public string ListFieldsText
        {
            get { return Utilities.JSONSerializer<Dictionary<string, string>>(FieldList); }
            set { FieldList = Utilities.JSONDeserializer<Dictionary<string, string>>(value); }
        }

        public AWPListItem()
        {
            this.ExportMode = WebPartExportMode.All;
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
        }

        protected override void Render(HtmlTextWriter writer)
        {
            try
            {
                this.EnsureChildControls();
                StringBuilder sb = new StringBuilder();
                string template = this.HtmlContent;
                string folderName = string.Empty;
                Guid itemID = Guid.Empty;


                //ShowMe Validation
                if (this.EnableShow && SPContext.Current.FormContext.FormMode != SPControlMode.Edit)
                {
                    if (string.IsNullOrEmpty(this.ShowQueryStringParameter) ||
                        !this.Page.Request.QueryString.HasKeys() || 
                        !this.Page.Request.QueryString[this.ShowQueryStringParameter].Equals(this.ShowQueryStringParameterValue))
                    {
                        this.Visible = false;
                        return;
                    }
                }

                //HideMe Validation
                if (this.EnableHide && SPContext.Current.FormContext.FormMode != SPControlMode.Edit)
                {
                    if (!string.IsNullOrEmpty(this.HideQueryStringParameter) &&
                        this.Page.Request.QueryString.HasKeys() &&
                        this.Page.Request.QueryString[this.HideQueryStringParameter].Equals(this.HideQueryStringParameterValue))
                    {
                        this.Visible = false;
                        return;
                    }
                }

                #region Opening Container Type
                if (IsIDEnabled)
                    writer.AddAttribute(HtmlTextWriterAttribute.Id, ContainterID);
                if (IsClassEnabled)
                    writer.AddAttribute(HtmlTextWriterAttribute.Class, ContainerClass);

                writer.RenderBeginTag(HtmlTextWriterTag.Div);
                #endregion

                #region Header Container
                if (!string.IsNullOrEmpty(HeaderContent))
                {
                    writer.AddAttribute(HtmlTextWriterAttribute.Class, "header");
                    writer.RenderBeginTag(HtmlTextWriterTag.Div);
                    writer.WriteLine(HeaderContent);
                    writer.RenderEndTag();
                }

                #endregion

                if (string.IsNullOrEmpty(ItemParameter) || !this.Page.Request.QueryString.HasKeys() || string.IsNullOrEmpty(this.Page.Request.QueryString[this.ItemParameter]))
                {
                    //Handle error here
                    if (string.IsNullOrEmpty(EmptyTemplate))
                    {
                        writer.AddStyleAttribute(HtmlTextWriterStyle.Color, "red");
                        writer.RenderBeginTag(HtmlTextWriterTag.Span);
                        writer.WriteEncodedText("No item to display");
                        writer.RenderEndTag();

                    }
                    else
                    {
                        writer.Write(EmptyTemplate);
                        
                    }
                    writer.RenderEndTag();
                    return;
                }
                else
                {
                    itemID = new Guid(this.Page.Request.QueryString[ItemParameter]);
                }
                Guid folderID = Guid.Empty;

                if (!EnableFolderParameter && (string.IsNullOrEmpty(FolderParameter) || !this.Page.Request.QueryString.HasKeys() || string.IsNullOrEmpty(this.Page.Request.QueryString[this.FolderParameter])))
                {

                }
                else
                {
                    folderID = new Guid(this.Page.Request.QueryString[FolderParameter]);
                }

                if (!string.IsNullOrEmpty(ListName))
                {
                    
                    SPList list = SPContext.Current.Web.Lists.GetList(new Guid(this.ListName), false); ;

                    if (list != null)
                    {
                        #region Main Rendering


                        SPListItem superItem = list.GetItemByUniqueId(itemID);
                        if (superItem != null)
                        {
                            //Filling and Replacing Template
                            sb.Remove(0, sb.Length);
                            sb.Append(template);

                            if (template.IndexOf("[#FolderName]") >= 0)
                            {
                                if (superItem.File != null)
                                    sb.Replace("[#FolderName]", superItem.File.ParentFolder.Name);
                                else if (superItem.Folder != null)
                                    sb.Replace("[#FolderName]", superItem.Folder.Name);
                                else
                                    sb.Replace("[#FolderName]", list.Title);

                            }

                            foreach (var key in FieldList)
                            {

                                if (list.Fields.GetFieldByInternalName(key.Value).Type == SPFieldType.Calculated)
                                    sb.Replace(key.Key, superItem.GetFormattedValue(key.Value));
                                else
                                    sb.Replace(key.Key, Convert.ToString(superItem[key.Value]));
                            }

                            if (EnablePreviusNextLinks)
                            {
                                string previus = "", next = "";
                                string folderParam = "";
                                string enableShow = "";

                                List<string> itemsonList = null;
                                if (GotNext || GotPrevious)
                                {
                                    SPListItemCollection items = null;
                                    SPView view = null;
                                    if (IsByView)
                                        view = list.GetView(new Guid(ViewName));
                                    else
                                        view = list.DefaultView;

                                    SPQuery query = new SPQuery(view);
                                    query.ViewFields = "<FieldRef Name=\"ID\"/>";
                                    if (EnableFolderParameter && folderID != Guid.Empty)
                                    {
                                        //SPListItem folder = list.Folders.GetItemById(folderID);
                                        var res = list.Folders[folderID];
                                        if (res != null && res.FileSystemObjectType == SPFileSystemObjectType.Folder)
                                            query.Folder = res.Folder;
                                    }
                                    items = list.GetItems(query);

                                    itemsonList = new List<string>();
                                    foreach (SPListItem item in items)
                                        itemsonList.Add(item.UniqueId.ToString());

                                    int pos = itemsonList.IndexOf(itemID.ToString());
                                    if (pos > 0)
                                        previus = itemsonList[pos - 1];
                                    if (pos < itemsonList.Count - 1)
                                        next = itemsonList[pos + 1];

                                    if (EnableFolderParameter && folderID != Guid.Empty)
                                        folderParam = string.Format("&{0}={1}", FolderParameter, folderID);

                                    if (EnableShow && !string.IsNullOrEmpty(ShowQueryStringParameter) && !string.IsNullOrEmpty(ShowQueryStringParameterValue))
                                        enableShow = string.Format("&{0}={1}", ShowQueryStringParameter, ShowQueryStringParameterValue);

                                }
                                if (GotPrevious)
                                {
                                    System.Web.UI.HtmlControls.HtmlAnchor anchorPrevius = new System.Web.UI.HtmlControls.HtmlAnchor();
                                    anchorPrevius.ID = "previus";
                                    if (string.IsNullOrEmpty(previus))
                                    {
                                        anchorPrevius.Attributes.Add("class", "disabled");
                                        anchorPrevius.HRef = "#";
                                    }
                                    else
                                    {
                                        anchorPrevius.HRef = string.Format("{0}?{1}={2}{3}{4}", this.Page.Request.Url.AbsolutePath, ItemParameter, previus, folderParam, enableShow);
                                    }
                                    anchorPrevius.InnerText = PreviusText;
                                    sb.Replace("[Previus]", Utilities.RenderControl(anchorPrevius));
                                }
                                if (GotNext)
                                {
                                    System.Web.UI.HtmlControls.HtmlAnchor anchorNext = new System.Web.UI.HtmlControls.HtmlAnchor();
                                    anchorNext.ID = "next";
                                    if (string.IsNullOrEmpty(next))
                                    {
                                        anchorNext.Attributes.Add("class", "disabled");
                                        anchorNext.HRef = "#";
                                    }
                                    else
                                    {
                                        anchorNext.HRef = string.Format("{0}?{1}={2}{3}{4}", this.Page.Request.Url.AbsolutePath, ItemParameter, next, folderParam, enableShow);


                                    }
                                    anchorNext.InnerText = NextText;
                                    sb.Replace("[Next]", Utilities.RenderControl(anchorNext));
                                }
                            }

                            writer.RenderBeginTag(HtmlTextWriterTag.Div);
                            writer.WriteLine(sb.ToString());
                            writer.RenderEndTag();
                        }
                        #endregion
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(EmptyTemplate))
                        {
                            writer.AddStyleAttribute(HtmlTextWriterStyle.Color, "red");
                            writer.RenderBeginTag(HtmlTextWriterTag.Span);
                            writer.WriteEncodedText("No item to display");
                            writer.RenderEndTag();

                        }
                        else
                        writer.Write(EmptyTemplate);
                    }


                }
                else
                {
                    writer.WriteEncodedText("No list assigned");
                }
                //Closing Container
                writer.RenderEndTag();
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }

        }

        public override EditorPartCollection CreateEditorParts()
        {
            List<EditorPart> editors = new List<EditorPart>();
            editors.Add(new ListItemEditor() { ID = this.ID + "_CustomListItemContentEditor" });
            editors.Add(new ShowWebPartEditor() { ID = this.ID + "_ShowMeEditor" });
            editors.Add(new HideWebPartEditor() { ID = this.ID + "_HideMeEditor" });
            EditorPartCollection baseEditors = base.CreateEditorParts();
            return new EditorPartCollection(baseEditors, editors);
        }

        #region IShowableWebPart Members

        public bool EnableShow { get; set; }

        public string ShowQueryStringParameter { get; set; }

        public string ShowQueryStringParameterValue { get; set; }

        #endregion

        #region IHideableWebPart Members

        public bool EnableHide { get; set; }

        public string HideQueryStringParameter { get; set; }

        public string HideQueryStringParameterValue { get; set; }

        #endregion
    }
}